<?php

namespace common\models\open;

use Yii;

/**
 * This is the model class for table "{{%open_token}}".
 *
 * @property int $id
 * @property int $client_id 客户端应用ID
 * @property int $user_id 客户端应用ID
 * @property string $access_token AccessToken
 * @property string $scope 授权范围
 * @property int $expired_at 过期时间
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class OpenToken extends \common\db\ActiveRecord {

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%open_token}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['client_id', 'user_id', 'expired_at', 'created_at', 'updated_at'], 'integer'],
            [['access_token', 'scope'], 'string', 'max' => 64],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'client_id' => '客户端应用ID',
            'user_id' => '客户端应用ID',
            'access_token' => 'AccessToken',
            'scope' => '授权范围',
            'expired_at' => '过期时间',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function getUser($param) {
        return $this->hasOne(OpenUser::className(), ['id' => 'user_id']);
    }

    public function generateAccessToken() {
        $this->access_token = Yii::$app->security->generateRandomString();
        $this->expired_at = time() + 3600;
    }

    /**
     * 这个就是我们进行yii\filters\auth\QueryParamAuth调用认证的函数，下面会说到
     * @param type $accessToken
     * @param type $type
     * @return type
     */
    public static function loginByAccessToken($accessToken, $type) {
        //查询数据库中有没有存在这个token
        return static::find()->where([
            'and',
            ['access_token' => $accessToken],
            ['>', 'expired_at', time()]
        ])->one();
    }

}
